package com.uzai.console.service.jd.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.constants.UserExtKeys;
import com.uzai.common.entity.User;
import com.uzai.common.enums.IdentityEnum;
import com.uzai.common.enums.OrderReStatusEnum;
import com.uzai.common.enums.OrderStatusEnum;
import com.uzai.common.enums.SysMsgTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.orderreport.OrderReportDto;
import com.uzai.console.dto.jd.jdorder.*;
import com.uzai.console.dto.feign.jdorder.JdOrderBindDto;
import com.uzai.console.dto.feign.jdorder.JdOrderSettledDto;
import com.uzai.console.dto.feign.jdorder.JdOrderUnbindDto;
import com.uzai.console.dto.feign.jdorder.JdOrderUnfreezeDto;
import com.uzai.console.dto.tb.tborder.TbOrderDto;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.PriRuleVo;
import com.uzai.console.entity.es.RewardVo;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.JdOrderFeignService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.dto.HistoryTbOrderOptDto;
import com.uzai.console.service.jd.JdOrderService;
import com.uzai.console.service.jd.JdOrderSyncService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.useraccdetail.UserAccDetailService;
import com.uzai.console.vo.jd.jdorder.JdOrderInfoVo;
import com.uzai.console.vo.jd.jdorder.JdOrderReportVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.order.BaseOrderVo;
import com.uzai.console.vo.profit.ladderratio.LadderRatioInfoVo;
import com.uzai.console.vo.profit.normalrewardrule.NormalRewardRuleInfoVo;
import com.uzai.console.vo.profit.nuserrewardrule.NuserRewardRuleInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 京东订单
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class JdOrderServiceImpl implements JdOrderService {

    Logger logger = LoggerFactory.getLogger(JdOrderServiceImpl.class);

    @Autowired
    private JdOrderMapper jdOrderMapper;
    @Autowired
    private JdTokenMapper jdTokenMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JdOrderSyncService jdOrderSyncService;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private JdOrderFeignService jdOrderFeignService;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private LadderRatioGroupMapper ladderRatioGroupMapper;
    @Autowired
    private NormalRewardRuleMapper normalRewardRuleMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NuserRewardRuleGroupMapper nuserRewardRuleGroupMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private UserAccDetailService userAccDetailService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    /**
     * 查询京东订单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderQuery
     * @return null
     */
    public Page<JdOrderInfoVo> findJdOrderList(JdOrderQuery jdOrderQuery){

        //新建返回到页面的LIST对象
        List<JdOrderInfoVo> jdOrderInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<JdOrder> page = new Page<>();
        jdOrderQuery.convert(page);
        List<JdOrder> jdOrderList = jdOrderMapper.findByList(page, jdOrderQuery);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                JdOrderInfoVo jdOrderInfoVo = new JdOrderInfoVo();
                BeanUtils.copyProperties(jdOrder, jdOrderInfoVo);

                //查询机器人信息
                Device device = deviceService.findDeviceInfoByDeviceUniqueId(jdOrder.getDeviceUniqueId(), jdOrder.getDeviceType(), jdOrder.getMerId());
                if(device != null){
                    jdOrderInfoVo.setDeviceId(device.getDeviceId());
                    jdOrderInfoVo.setDeviceName(device.getDeviceName());
                    jdOrderInfoVo.setDeviceRemark(device.getDeviceRemark());
                }

                jdOrderInfoVoList.add(jdOrderInfoVo);
            }
        }
        //返回到页面分页对象
        Page<JdOrderInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(jdOrderInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询京东订单详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderIdDto
     * @return null
     */
    public JdOrderInfoVo findJdOrderInfo(JdOrderIdDto jdOrderIdDto){
        //返回到页面的VO对象
        JdOrderInfoVo jdOrderInfoVo = new JdOrderInfoVo();

        if(jdOrderIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入订单ID");
        }

        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderIdDto.getId(), jdOrderIdDto.getMerId());

        if(jdOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单id不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(jdOrder, jdOrderInfoVo);

        //通过会员ID查询会员类型信息
        User user = userService.findUserInfo(jdOrder.getUserId(), jdOrder.getDeviceType(), jdOrder.getMerId());
        if(user != null){
            jdOrderInfoVo.setIdentity(user.getIdentity());

            IdentityEnum identityEnum = IdentityEnum.getById(user.getIdentity());
            if(identityEnum != null){
                jdOrderInfoVo.setIdentityName(identityEnum.getDesc());
            }

            UserType userType = userTypeMapper.selectById(user.getUserType(), jdOrderIdDto.getMerId());
            if(userType != null){
                jdOrderInfoVo.setUserTypeName(userType.getName());
            }
        }

        //查询机器人信息
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(jdOrder.getDeviceUniqueId(), jdOrder.getDeviceType(), jdOrderIdDto.getMerId());
        if(device != null){
            jdOrderInfoVo.setDeviceId(device.getDeviceId());
            jdOrderInfoVo.setDeviceName(device.getDeviceName());
            jdOrderInfoVo.setDeviceRemark(device.getDeviceRemark());
        }

        //通过联盟alimmId查询联盟信息，得到联盟账号名称
        if(StringUtils.isNotBlank(jdOrder.getUnionId())){
            JdToken jdToken = jdTokenMapper.selectByUnionId(jdOrder.getUnionId());
            if(jdToken != null){
                if(StringUtils.isNotBlank(jdToken.getRemark())){
                    String unionId = jdToken.getUnionId() + "（" + jdToken.getRemark() + "）";
                    jdOrderInfoVo.setUnionId(unionId);
                }
            }
        }

        //封装分佣信息
        //ESID为运营商id_父订单号_子订单号
        String es_id = jdOrder.getMerId() + "_" + jdOrder.getParentOrderNo() + "_" + jdOrder.getChildOrderNo();
        try {
            Map<String, Object> orderEsMap = elasticsearchUtil.searchDataById(EsIndexName.UZAI_ORDER_REWARD_INFO, es_id, null);
            RewardVo rewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(orderEsMap)), RewardVo.class);
            if(rewardVo != null){

                //定向规则
                PriRuleVo priRule = rewardVo.getPriRule();
                if(priRule != null){
                    //阶梯规则组ID
                    LadderRatioInfoVo ladderRatio = priRule.getLadderRatio();
                    if(ladderRatio != null){
                        Long groupId = ladderRatio.getGroupId();
                        if(groupId != null){
                            LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(groupId, jdOrderIdDto.getMerId());
                            if(ladderRatioGroup != null){
                                ladderRatio.setGroupName(ladderRatioGroup.getName());
                            }
                        }

                    }
                }

                //杀熟规则
                NuserRewardRuleInfoVo nuserRewardRule = rewardVo.getNuserRewardRule();
                if(nuserRewardRule != null){

                    //杀熟规则组
                    Long nuserRewardGroupId = nuserRewardRule.getGroupId();
                    if(nuserRewardGroupId != null){
                        NuserRewardRuleGroup nuserRewardRuleGroup = nuserRewardRuleGroupMapper.selectById(nuserRewardGroupId, jdOrderIdDto.getMerId());
                        if(nuserRewardRuleGroup != null){
                            nuserRewardRule.setGroupName(nuserRewardRuleGroup.getName());
                        }
                    }

                    //分佣规则ID
                    Long normalRewardRuleId = nuserRewardRule.getNormalRewardRuleId();
                    if(normalRewardRuleId != null){
                        NormalRewardRule normalRewardRule = normalRewardRuleMapper.selectById(normalRewardRuleId, jdOrderIdDto.getMerId());
                        if(normalRewardRule != null){
                            nuserRewardRule.setNormalRewardRuleName(normalRewardRule.getName());
                        }
                    }

                    //阶梯规则组ID
                    LadderRatioInfoVo ladderRatio = nuserRewardRule.getLadderRatio();
                    if(ladderRatio != null){
                        Long groupId = ladderRatio.getGroupId();
                        if(groupId != null){
                            LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(groupId, jdOrderIdDto.getMerId());
                            if(ladderRatioGroup != null){
                                ladderRatio.setGroupName(ladderRatioGroup.getName());
                            }
                        }

                    }
                }

                //分佣规则
                NormalRewardRuleInfoVo normalRewardRule = rewardVo.getNormalRewardRule();
                if(normalRewardRule != null){
                    //阶梯规则组ID
                    LadderRatioInfoVo ladderRatio = normalRewardRule.getLadderRatio();
                    if(ladderRatio != null){
                        Long groupId = ladderRatio.getGroupId();
                        if(groupId != null){
                            LadderRatioGroup ladderRatioGroup = ladderRatioGroupMapper.selectById(groupId, jdOrderIdDto.getMerId());
                            if(ladderRatioGroup != null){
                                ladderRatio.setGroupName(ladderRatioGroup.getName());
                            }
                        }
                    }

                    //计算分佣总佣金（扣除N%之后的佣金）
                    //订单总佣金
                    Double commission = jdOrder.getCommission();
                    if(commission != null){
                        //扣除N%的计算总佣金（默认等于订单总佣金）
                        Double rewardSub = commission;
                        //分佣规则里配置的扣除N%比例
                        Double rewardSubRatio = normalRewardRule.getRewardSubRatio();
                        if(rewardSubRatio != null){
                            rewardSub = Math.mul(commission, (1 - normalRewardRule.getRewardSubRatio()/100));
                        }
                        normalRewardRule.setCalculateCommission(rewardSub);
                    }
                }

                //买家
                RewardVo.ReDetail reDetail = rewardVo.getReUser();
                if(reDetail != null){
                    User reUser = userService.findUserInfo(reDetail.getUserId(), jdOrder.getDeviceType(), jdOrderIdDto.getMerId());
                    if(reUser != null){
                        reDetail.setUserName(reUser.getNickName());
                    }
                }

                //合伙人
                RewardVo.ReDetail rePartner = rewardVo.getRePartner();
                if(rePartner != null){
                    User rePartnerUser = userService.findUserInfo(rePartner.getUserId(), jdOrder.getDeviceType(), jdOrderIdDto.getMerId());
                    if(rePartnerUser != null){
                        rePartner.setUserName(rePartnerUser.getNickName());
                    }
                }

                //代理人
                RewardVo.ReDetail reAgent = rewardVo.getReAgent();
                if(reAgent != null){
                    User reAgentUser = userService.findUserInfo(reAgent.getUserId(), jdOrder.getDeviceType(), jdOrderIdDto.getMerId());
                    if(reAgentUser != null){
                        reAgent.setUserName(reAgentUser.getNickName());
                    }
                }

                //上级代理人
                RewardVo.ReDetail reSlAgent = rewardVo.getReSlAgent();
                if(reSlAgent != null){
                    User reSlAgentUser = userService.findUserInfo(reSlAgent.getUserId(), jdOrder.getDeviceType(), jdOrderIdDto.getMerId());
                    if(reSlAgentUser != null){
                        reSlAgent.setUserName(reSlAgentUser.getNickName());
                    }
                }

                //买家上级
                RewardVo.ReDetail reParent = rewardVo.getReParent();
                if(reParent != null){
                    User reParentUser = userService.findUserInfo(reParent.getUserId(), jdOrder.getDeviceType(), jdOrderIdDto.getMerId());
                    if(reParentUser != null){
                        reParent.setUserName(reParentUser.getNickName());
                    }
                }

                //买家上上级
                RewardVo.ReDetail reSlParent = rewardVo.getReSlParent();
                if(reSlParent != null){
                    User reSlParentUser = userService.findUserInfo(reSlParent.getUserId(), jdOrder.getDeviceType(), jdOrderIdDto.getMerId());
                    if(reSlParentUser != null){
                        reSlParent.setUserName(reSlParentUser.getNickName());
                    }
                }

                //N级
                List<RewardVo.ReDetail> reOthers = rewardVo.getReOthers();
                if(reOthers != null && reOthers.size() > 0){
                    for (RewardVo.ReDetail reOther : reOthers){
                        if(reOther != null){
                            User reOtherUser = userService.findUserInfo(reOther.getUserId(), jdOrder.getDeviceType(), jdOrderIdDto.getMerId());
                            if(reOtherUser != null){
                                reOther.setUserName(reOtherUser.getNickName());
                            }
                        }
                    }
                }

            }
            jdOrderInfoVo.setRewardVo(rewardVo);
        }catch(Exception e){
            logger.error("-----order uzai_order_reward_info of ES is not exit {}", e.getMessage());
        }

        return  jdOrderInfoVo;
    }

    /**
     * 查询京东订单统计信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderQuery
     * @return null
     */
    public JdOrderReportVo findJdOrderReport(JdOrderQuery jdOrderQuery){

        //获取订单状态枚举,不包括失效订单
        OrderStatusEnum[] orderStatusEnums = OrderStatusEnum.values();
        if(orderStatusEnums != null && orderStatusEnums.length > 0 ){
            //查询订单状态
            List<Integer> statusList = jdOrderQuery.getStatusList();
            if(statusList == null || statusList.size() == 0){
                statusList = new ArrayList<>();
                for (OrderStatusEnum orderStatusEnum : orderStatusEnums) {
                    //不包括失效订单
                    if(orderStatusEnum.getValue().intValue() != OrderStatusEnum.STATUS_INVALID.getValue().intValue()){
                        statusList.add(orderStatusEnum.getValue());
                    }
                }
            }else{
                statusList.remove(OrderStatusEnum.STATUS_INVALID.getValue().intValue());
            }
            jdOrderQuery.setStatusList(statusList);
        }

        return jdOrderMapper.findJdOrderReport(jdOrderQuery);
    }

    /**
     * 京东订单删除-假删除（修改是否删除状态）
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderDelDto
     * @return null
     */
    public Boolean delJdOrder(JdOrderDelDto jdOrderDelDto){

        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderDelDto.getId(), jdOrderDelDto.getMerId());
        if(jdOrder == null){
            throw new BusinessException("订单不存在或是3个月之前的订单");
        }

        jdOrderMapper.deleteById(jdOrderDelDto.getId(), jdOrderDelDto.getMerId());

        //发送MQ，修改订单统计数据
        if(jdOrder.getUserId() != null){
            String userExtKey_jd = null;
            String userExtKey = null;
            if(jdOrder.getStatus().intValue() == OrderStatusEnum.STATUS_PAID_VALUE) { //付款订单
                userExtKey_jd = UserExtKeys.JdPayOrderCount;
                userExtKey = UserExtKeys.PayOrderCount;
            }else if(jdOrder.getStatus().intValue() == OrderStatusEnum.STATUS_SETTLED_VALUE){ //结算状态
                userExtKey_jd = UserExtKeys.JdSettleOrderCount;
                userExtKey = UserExtKeys.SettleOrderCount;
            }
            //不等于空，才发送MQ
            if(StringUtils.isNotBlank(userExtKey_jd)){
                OrderReportDto orderReportDto = new OrderReportDto();
                orderReportDto.setId(Tools.getStr(jdOrder.getParentOrderNo()) + Tools.getStr(jdOrder.getChildOrderNo()));
                orderReportDto.setKeys(Lists.newArrayList(userExtKey_jd, userExtKey));
                orderReportDto.setMerId(jdOrder.getMerId());
                orderReportDto.setUserId(jdOrder.getUserId());
                orderReportDto.setVal(-1);
                noticeMsgPushProducerService.sendOrderReportAsync(orderReportDto);
            }
        }

        return true;

    }

    /**
     * 确认收货
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderIdDto
     * @return null
     */
    public Boolean confirmReceive(JdOrderIdDto jdOrderIdDto){

        if(jdOrderIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询京东订单
        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderIdDto.getId(), jdOrderIdDto.getMerId());

        if(jdOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        //查询用户是否存在
        if(jdOrder.getUserId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未绑定会员");
        }

        //订单状态为0-付款状态时，才能确认收货
        if(jdOrder.getStatus() == 0){
            //调用确认收货接口
            JdOrderSettledDto jdOrderSettledDto = new JdOrderSettledDto();
            jdOrderSettledDto.setMerId(jdOrder.getMerId());
            jdOrderSettledDto.setOrderId(jdOrder.getParentOrderNo());
            jdOrderSettledDto.setChildOrderId(jdOrder.getChildOrderNo());
            UzaiRespVo<Object> result =  jdOrderFeignService.settled(jdOrderSettledDto);
            logger.info("---京东订单确认收货---dto={}, result={}" ,JSONObject.toJSONString(jdOrderSettledDto), JSONObject.toJSONString(result));
            if(result.getCode() != 200){
                throw  new BusinessException(result.getCode(), result.getMsg());
            }
        }
        return true;
    }

    /**
     * 手动维权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderIdDto
     * @return null
     */
    public Boolean confirmRefund(JdOrderIdDto jdOrderIdDto){

        if(jdOrderIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询京东订单
        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderIdDto.getId(), jdOrderIdDto.getMerId());

        if(jdOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        //订单状态为1-结算状态时，才能手动维权
        if(jdOrder.getStatus() == 1){
            //调用确认维权接口
        }

        return true;
    }

    /**
     * 订单冻结
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderIdDto
     * @return null
     */
    public Boolean confirmFrozen(JdOrderIdDto jdOrderIdDto){
        if(jdOrderIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询京东订单
        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderIdDto.getId(), jdOrderIdDto.getMerId());

        if(jdOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        //订单状态为0-付款状态时，才能冻结
        if(jdOrder.getStatus() == 0){
            //调用订单冻结接口
            return true;
        }
        return false;
    }

    /**
     * 订单解冻
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderIdDto
     * @return null
     */
    public Boolean confirmThaw(JdOrderIdDto jdOrderIdDto){
        if(jdOrderIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询京东订单
        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderIdDto.getId(), jdOrderIdDto.getMerId());

        if(jdOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        //订单返利状态为3-返利冻结时，才能解冻
        if(jdOrder.getReStatus() == 3){
            //调用确认解冻接口
            JdOrderUnfreezeDto jdOrderUnfreezeDto = new JdOrderUnfreezeDto();
            jdOrderUnfreezeDto.setMerId(jdOrder.getMerId());
            jdOrderUnfreezeDto.setOrderId(jdOrder.getParentOrderNo());
            jdOrderUnfreezeDto.setChildOrderId(jdOrder.getChildOrderNo());
            UzaiRespVo<Object> result =  jdOrderFeignService.unfreeze(jdOrderUnfreezeDto);
            logger.info("---京东订单确认解冻---dto={}, result={}" ,JSONObject.toJSONString(jdOrderUnfreezeDto), JSONObject.toJSONString(result));
            if(result.getCode() != 200){
                throw  new BusinessException(result.getCode(), result.getMsg());
            }
        }
        return true;
    }

    /**
     * 订单解绑用户
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderUnbindUserDto
     * @return null
     */
    public Boolean unbindUser(JdOrderUnbindUserDto jdOrderUnbindUserDto){

        if(jdOrderUnbindUserDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询京东订单
        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderUnbindUserDto.getId(), jdOrderUnbindUserDto.getMerId());

        if(jdOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        //订单未绑定用户
        if(jdOrder.getUserId() != null){

            //调用确认解绑接口
            JdOrderUnbindDto jdOrderUnbindDto = new JdOrderUnbindDto();
            jdOrderUnbindDto.setMerId(jdOrder.getMerId());
            jdOrderUnbindDto.setOrderId(jdOrder.getParentOrderNo());
            jdOrderUnbindDto.setChildOrderId(jdOrder.getChildOrderNo());
            UzaiRespVo<Object> result =  jdOrderFeignService.unbind(jdOrderUnbindDto);
            logger.info("---京东订单解绑用户---dto={}, result={}" ,JSONObject.toJSONString(jdOrderUnbindDto), JSONObject.toJSONString(result));

            //AOP切面，封装操作日志内容
            String aspectOperatorLog = "京东订单解绑会员。订单号:"+jdOrder.getChildOrderNo()+";会员id：" + jdOrder.getUserId();
            jdOrderUnbindUserDto.setAspectOperatorLog(aspectOperatorLog);

            if(result.getCode() != 200){
                throw  new BusinessException(result.getCode(), result.getMsg());
            }
        }
        return true;
    }

    /**
     * 订单绑定用户
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderBindUserDto
     * @return null
     */
    public Boolean bindUser(JdOrderBindUserDto jdOrderBindUserDto){
        if(jdOrderBindUserDto.getId() == null || jdOrderBindUserDto.getUserId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询京东订单
        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderBindUserDto.getId(), jdOrderBindUserDto.getMerId());
        if(jdOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
        }

        if(Tools.getInteger(jdOrder.getStatus()).intValue() != OrderStatusEnum.STATUS_PAID_VALUE){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有付款状态才能绑定会员");
        }

        //查询用户是否存在
        User user = userService.findUserInfo(jdOrderBindUserDto.getUserId(), jdOrder.getDeviceType(), jdOrderBindUserDto.getMerId());
        if(user == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NO_USER);
        }

        //调用确认绑定用户接口
        JdOrderBindDto jdOrderBindDto = new JdOrderBindDto();
        jdOrderBindDto.setMerId(jdOrder.getMerId());
        jdOrderBindDto.setOrderId(jdOrder.getParentOrderNo());
        jdOrderBindDto.setChildOrderId(jdOrder.getChildOrderNo());
        jdOrderBindDto.setBizUserId(user.getBizUserId());
        jdOrderBindDto.setDeviceUniqueId(user.getDeviceUniqueId());
        jdOrderBindDto.setDeviceType(user.getRegSource());
        UzaiRespVo<Object> result =  jdOrderFeignService.bind(jdOrderBindDto);

        logger.info("---发送修改京东订单绑定会员-para={}, result={}", JSONObject.toJSONString(jdOrderBindDto), JSONObject.toJSONString(result));

        if(result.getCode() != 200){
            throw  new BusinessException(result.getCode(), result.getMsg());
        }

        //发送绑定订单异常提醒通知
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(jdOrderBindUserDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_ORDER_BIND.getValue()); //修改绑定订单会员
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, jdOrderBindUserDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        ext.put("childuser", loginVo.getLoginName());
        ext.put("orderid", jdOrder.getChildOrderNo());
        ext.put("nick", user.getNickName());
        ext.put("wxid", user.getBizUserId());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送订单修改绑定会员消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));
        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
        return true;
    }

    /**
     * 修改解冻时间
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderThawTimeDto
     * @return null
     */
    public Boolean updateThawTime(JdOrderThawTimeDto jdOrderThawTimeDto){
        try {
            if(jdOrderThawTimeDto.getId() == null || jdOrderThawTimeDto.getUnfreezeTime() == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
            }

            //查询京东订单
            JdOrder jdOrder = jdOrderMapper.selectById(jdOrderThawTimeDto.getId(), jdOrderThawTimeDto.getMerId());

            if(jdOrder == null ){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ORDER_IS_NULL);
            }
            //设置修改时间
            jdOrderThawTimeDto.setUpdateTime(DateUtil.getNowTime());
            jdOrderMapper.updateThawTime(jdOrderThawTimeDto);
            return true;
        }catch (Exception e){
            logger.error("-----updateStateById is error {}", e.getMessage());
            return false;
        }
    }

    /**
     * 手动下载京东订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrder(JdOrderDownLoadDto jdOrderDownLoadDto) {

        if (jdOrderDownLoadDto.getQueryTimeType() == null || jdOrderDownLoadDto.getQueryStartTime() == null || jdOrderDownLoadDto.getQueryEndTime() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //判断开始时间是否小于90天前
        Integer now = DateUtil.getNowTime();
        if(now - jdOrderDownLoadDto.getQueryStartTime() > 7776000){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于90天前");
        }

        //日期范围只能是7天内
        if(jdOrderDownLoadDto.getQueryStartTime() < (jdOrderDownLoadDto.getQueryEndTime()-604800)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "日期范围只能是7天内");
        }

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.JD_DOWNLOAD_ORDER_OPE, jdOrderDownLoadDto.getMerId()));

        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"2分钟只允许一次下载请求");
        }

        //异步后台调用订单远程下载
        jdOrderSyncService.downloadOrderListSync(jdOrderDownLoadDto);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.JD_DOWNLOAD_ORDER_OPE,jdOrderDownLoadDto.getMerId()),jdOrderDownLoadDto.getMerId()+"",2, TimeUnit.MINUTES);

    }

    /**
     * 通过API手动下载京东订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderApiDownLoadDto
     * @return null
     */
    public void downloadOrderApi(JdOrderApiDownLoadDto jdOrderApiDownLoadDto){
        if (jdOrderApiDownLoadDto.getQueryTimeType() == null || jdOrderApiDownLoadDto.getQueryStartTime() == null || jdOrderApiDownLoadDto.getQueryEndTime() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //判断开始时间是否小于90天前
        Integer now = DateUtil.getNowTime();
        if(now - jdOrderApiDownLoadDto.getQueryStartTime() > 7776000){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于90天前");
        }

        //日期范围只能是3天内
        if(jdOrderApiDownLoadDto.getQueryStartTime() < (jdOrderApiDownLoadDto.getQueryEndTime()- 3*24*3600)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "日期范围只能是3天之内");
        }

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.JD_DOWNLOAD_ORDER_API, jdOrderApiDownLoadDto.getMerId()));

        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"提交频繁，请1分钟后重新提交！");
        }

        //异步后台调用订单远程下载
        jdOrderSyncService.downloadOrderApiListSync(jdOrderApiDownLoadDto);

        //往reids插入本次下载，允许1分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.JD_DOWNLOAD_ORDER_API,jdOrderApiDownLoadDto.getMerId()),jdOrderApiDownLoadDto.getMerId()+"",60, TimeUnit.SECONDS);
    }


    /**
     * 刷新京东订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderIdDto
     * @return null
     */
    @Override
    public void refreshOrder(JdOrderIdDto jdOrderIdDto){
        if (jdOrderIdDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        JdOrder jdOrder =  jdOrderMapper.selectById(jdOrderIdDto.getId(), jdOrderIdDto.getMerId());

        //判断订单存在或者已删除
        if(jdOrder == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"订单不存在或已删除");
        }

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.JD_REFRESH_ORDER_OPE, jdOrder.getMerId()));

        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"5分钟只允许一次刷新请求");
        }


        //2024-01-12修改
        //当佣金=0,且状态为已结算/返利（status=1）要先把状态改为付款/未返利(status=0,re_status=0)，结算时间改为0(accountdt=0) 后再同步
        if(Tools.getDouble(jdOrder.getCommission()).doubleValue() == 0.00D
         && Tools.getInteger(jdOrder.getStatus()) == OrderStatusEnum.STATUS_SETTLED.getValue()){
            jdOrder.setStatus(OrderStatusEnum.STATUS_PAID.getValue()); //已付款
            jdOrder.setReStatus(OrderReStatusEnum.RE_STATUS_NO.getValue());  //未返利
            jdOrder.setAccountdt(0);   //结算时间为0
            jdOrder.setUpdateTime(DateUtil.getNowTime());
            jdOrderMapper.updateByIdSelective(jdOrder);
        }

        //异步后台调用订单远程下载
        jdOrderSyncService.updateJdOrder(jdOrder);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.JD_DOWNLOAD_ORDER_OPE,jdOrder.getMerId()),jdOrder.getMerId()+"",5, TimeUnit.MINUTES);

    }

    /**
     * 查询所有未绑定用户订单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderUnbindDtoQuery
     * @return null
     */
    public Page<JdOrderInfoVo> findUnbindUserList(JdOrderUnbindDtoQuery jdOrderUnbindDtoQuery){

        //新建返回到页面的LIST对象
        List<JdOrderInfoVo> jdOrderInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<JdOrder> page = new Page<>();
        jdOrderUnbindDtoQuery.convert(page);
        List<JdOrder> jdOrderList = jdOrderMapper.findUnbindUserList(page, jdOrderUnbindDtoQuery);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                JdOrderInfoVo jdOrderInfoVo = new JdOrderInfoVo();
                BeanUtils.copyProperties(jdOrder, jdOrderInfoVo);
                jdOrderInfoVoList.add(jdOrderInfoVo);
            }
        }
        //返回到页面分页对象
        Page<JdOrderInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(jdOrderInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询所有未绑定用户订单统计信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderUnbindDtoQuery
     * @return null
     */
    public JdOrderReportVo findUnbindUserReport(JdOrderUnbindDtoQuery jdOrderUnbindDtoQuery){
        return jdOrderMapper.findUnbindUserReport(jdOrderUnbindDtoQuery);
    }

    /**
     * 删除所有未绑定用户订单-假删除（修改是否删除状态）
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderDeleteUnbindDto
     * @return jdOrderUnbindDtoQuery
     */
    public Boolean deleteUnbindUserList(JdOrderDeleteUnbindDto jdOrderDeleteUnbindDto){
        try {
            jdOrderMapper.deleteUnbindUserList(jdOrderDeleteUnbindDto);
            return true;
        }catch (Exception e){
            logger.error("-----deleteUnbindUserList is error {}", e.getMessage());
            return false;
        }
    }


    /**
     * 追回返利
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderIdDto
     * @return null
     */
    @Transactional
    public Boolean rebateRefound(JdOrderIdDto jdOrderIdDto){

        if(jdOrderIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        //查询订单
        JdOrder jdOrder = jdOrderMapper.selectById(jdOrderIdDto.getId(), jdOrderIdDto.getMerId());

        if(jdOrder == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单不存在");
        }

        if(jdOrder.getReStatus() != 1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单状态不是已返利状态");
        }

        int now = DateUtil.getNowTime();

        //正常订单，立即修改
        jdOrder.setStatus(OrderStatusEnum.STATUS_REFUND_SUCCESS_VALUE); //维权成功
        jdOrder.setReStatus(OrderReStatusEnum.RE_STATUS_BACK_VALUE);    //已追回
        jdOrder.setRefundFinishTime(now);
        jdOrder.setUpdateTime(now);
        int i = jdOrderMapper.updateByIdSelective(jdOrder);
        //修改状态成功
        if(i == 1){
            //绑定会员
            if(jdOrder.getUserId() != null){
                //运营商id
                Long merId = jdOrder.getMerId();
                //父订单号
                String parentOrderNo = jdOrder.getParentOrderNo();
                //子订单号
                String childOrderNo = jdOrder.getChildOrderNo();
                //会员id
                Long userId = jdOrder.getUserId();
                //机器人类型
                String deviceType = jdOrder.getDeviceType();
                //机器人唯一id
                Long deviceUniqueId = jdOrder.getDeviceUniqueId();
                //用户积分
                int reUserInte = Tools.getInteger(jdOrder.getReUserInte());
                //用户返利
                double reUserBal = jdOrder.getReUserBal();
                //上级返利
                double reParentUserBal = jdOrder.getReParentBal();
                //上上级返利
                double reSlParentUserBal = jdOrder.getReSlParentBal();
                //代理返利
                double reAgentBal = jdOrder.getReAgentBal();
                //上级代理返利
                double reSlAgentBal = jdOrder.getReSlAgentBal();
                //合伙人返利
                double rePartnerBal = jdOrder.getRePartnerBal();

                //追回返利
                BaseOrderVo baseOrderVo = new BaseOrderVo();
                BeanUtils.copyProperties(jdOrder, baseOrderVo);
                userAccDetailService.updateByRebateRefound(merId, parentOrderNo, childOrderNo, userId, deviceType, deviceUniqueId,
                        reUserInte, reUserBal, reParentUserBal, reSlParentUserBal, reAgentBal, reSlAgentBal, rePartnerBal, now, baseOrderVo);
            }
        }

        return true;
    }

}
